extends Spatial

export (PackedScene) var lv #is null at the beginning
export (PackedScene) var player

#onready var camera_position = get_node("CameraPosition")

var lv1
var player1
var has_game_started

#FIXME: this is not the name, it is the path...
var current_lv_name
var current_spawn_name


func _ready():
	pass



func _process(delta):
	
	pass
	#print ("world is running")
	
	

func set_level(name, spawn, save):
	#print ("world:set_level")
	current_lv_name = name
	current_spawn_name = spawn
	lv = load(name)
	if lv == null:
		#FIXME: better error handling, do this is global.gd - before entering the world scene
		print ("MapNotFoundError!")
	else:
		init_world(save)
	
func init_world(save):
	has_game_started = false
	#FIXME: check if given spawn exists in the world BEFORE creating the world.
	
	create_world()
	spawn_player()
	#get_node("/root/Save").save_game()
	if save == true:
		print ("save!!!")
		get_node("/root/Save").save_node_data(self)
		

	
func create_world():
	#lv1.queue_free()

	lv1 = lv.instance()
	
	add_child(lv1)
	
	var portals = get_tree().get_nodes_in_group("group_portal")
	for p in portals:
		#print (p)
		p.connect("on_level_change", self, "save_world_data")
	
	handle_spawners_on_load()
	handle_flowerspots_on_load()
	

func spawn_player():
	var spawnName = "Spawn_01"
	if current_spawn_name != null:
			spawnName = current_spawn_name
	else:
			current_spawn_name = spawnName
	if lv1 != null:
		#print("spawn: " + str(spawnName))
		
		var spawnNode = lv1.find_node(spawnName, true, false)
		if spawnNode != null:
			player1 = player.instance()
			
			player1.translation = spawnNode.translation
			player1.rotate_y(spawnNode.rotation.y)
			
			#camera_position.translation = player1.translation
			
			add_child(player1)
			

			
			
		else:
			print("level has no spawn")
	else:
		print("lv1 not loaded")

func save():
	var save_dict = {
		level = current_lv_name,
		spawn = current_spawn_name
	}
	return save_dict
	
func clear_data():
	print ("clear_data")
	var spawners = get_tree().get_nodes_in_group("group_spawner")
	for s in spawners:
		s.queue_free ( )
	var spots = get_tree().get_nodes_in_group("group_flowerspot")
	for s in spots:
		s.queue_free ( )
		

func reset_world():
	if lv1 != null:
		#print("respawn: " + str(current_spawn_name))
		
		var spawnNode = lv1.find_node(current_spawn_name, true, false)
		
		if spawnNode != null:
		
			player1.velocity = Vector3(0, 0, 0)
			player1.translation = spawnNode.translation
			player1.rotation_degrees = Vector3(90, 180, 180)
			player1.rotate_y(spawnNode.rotation.y)
			
			var collectorNode = player1.find_node("PlayerInventory", true, false)
			if collectorNode != null:
				collectorNode.reload()
				
			var spawners = get_tree().get_nodes_in_group("group_spawner")
			for s in spawners:
				if (s.spawned_object != null):
					var wr = weakref(s.spawned_object)
					if (wr.get_ref()):
						wr.get_ref().queue_free ( )
						

			
			handle_spawners_on_load()
			handle_flowerspots_on_load()
					
		
func save_world_data():
	#print ("world.gd::save_world_data called")
	var wsdNode = find_node("WorldSaveData", true, false)
	if wsdNode != null:
		wsdNode.save_world_data(str(current_lv_name).get_base_dir ( ).replace("res://Scenes/Maps/", ""))
		#res://Scenes/Maps/

#FIXME: get savedata: fix double / copied code
#FIXME: why savedata_values[1] - better by name than by number				
func handle_spawners_on_load():

	var node_name = str(current_lv_name).get_base_dir ( ).replace("res://Scenes/Maps/", "") + "WorldSaveData"
	var savedata = get_node("/root/Save").get_node_data_by_name(node_name)

	
	if savedata != null:
	
		var savedata_values = savedata.values()[0].values()
		print (savedata_values[0])
		

	
		var spawners = get_tree().get_nodes_in_group("group_spawner")
		for s in spawners:
			if (savedata_values[0].find(str(s.name)) >= 0):
				s.is_active = false
	
	var spawners = get_tree().get_nodes_in_group("group_spawner")
	for s in spawners:
		s.spawn()		
		
func handle_flowerspots_on_load():
	print ("handle_flowerspots_on_load")
	var node_name = str(current_lv_name).get_base_dir ( ).replace("res://Scenes/Maps/", "") + "WorldSaveData"
	var savedata = get_node("/root/Save").get_node_data_by_name(node_name)
	#print (savedata)
	var spots = get_tree().get_nodes_in_group("group_flowerspot")
	
	if savedata != null:
	
		var savedata_values = savedata.values()[0].values()
		#print (savedata_values[1])
		

	
		
		for s in spots:
			for sv in savedata_values[1]:
				
				if s.name == sv[0] and not s.is_queued_for_deletion():
					#print (sv[0])
					#print (sv[1])
					s.set_status(sv[1])
					print (s.name)
	var fStatus = find_node("FlowerspotStatus", true, false)
	if fStatus != null:
		fStatus.on_load()
	


		

